package com.atguigu.gmall.item.service.impl;

import com.atguigu.gmall.common.constant.RedisConstant;
import com.atguigu.gmall.feign.product.SkuInfoFeignClient;
import com.atguigu.gmall.item.service.BloomFilterService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class BloomFilterServiceImpl  implements BloomFilterService {




    // @Scheduled(cron = "0 30 3 */7 * ?")  //需要SpringBoot开启定时任务功能
    //1、定时触发； 秒 分 时 日 月 周
    //2、手动触发

    @Autowired
    RedissonClient redissonClient;


    @Autowired
    RBloomFilter<Object> skuIdBloom;

    @Autowired
    SkuInfoFeignClient skuInfoFeignClient;

    @Scheduled(cron = "0 30 3 */7 * ?")
    public void rebuildCron(){
        rebuildBloom(skuIdBloom,1000000,0.00001);
    }


    @Override
    public void rebuildBloom(RBloomFilter<Object> skuIdBloom,long expectedInsertions, double falseProbability) {


        //3、通知远程商品服务先查出这个集合
        try {
            //1、删除redis中的老布隆
            skuIdBloom.delete(); //删除

            //2、重新初始化
            boolean b = skuIdBloom.tryInit(expectedInsertions, falseProbability);
            System.out.println("布隆重新init:"+b);

            String ids = skuInfoFeignClient.getAllSkuIds(); //远程调用  Net异常
            //远程调用成功
            //4、导入初始数据，拿到所有系统skuId的集合
            RList<Long> list = redissonClient.getList(RedisConstant.SKUIDS_TEMP_LIST);
            Long temp = null;
            for (Long skuId : list) {
                System.out.println("正在给布隆添加："+skuId);
                skuIdBloom.add(skuId);
                temp = skuId;
            }
            System.out.println("布隆有?："+skuIdBloom.contains(temp));
            //5、删除redis中这个临时数据
            list.delete();//远程删除这个key
        }catch (Exception e){
            log.error("布隆重建错误：{}",e);
            throw  e;
        }
    }
}
